package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.common.anno.RequiresLogin;
import cn.wolfcode.luowowo.member.domain.Userinfo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if(! (handler instanceof HandlerMethod)) {
            return true;
        }
            //1.判断方法 是有需要登陆
            HandlerMethod method = (HandlerMethod) handler;
            RequiresLogin methodAnnotation = method.getMethodAnnotation(RequiresLogin.class);

        if(! (methodAnnotation instanceof RequiresLogin)){
            return true;
        }
        //2.要的话判断是否有登陆  没有的话回登录界面
        String key=null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            if ("token".equals(cookieName)) {
                key= cookie.getValue();
            }
        }

        if(key!=null) {
            String userinfo_str = redisTemplate.opsForValue().get(key);
            Userinfo userinfo = JSON.parseObject(userinfo_str, Userinfo.class);
            request.getSession().setAttribute("userInfo",userinfo);
            return true;
        }


            response.sendRedirect("/login.html");

        return false;
    }
}
